﻿using System;
using System.Windows;
using ThePresenter.Net.NetCom;
using ThePresenter.Properties;

namespace ThePresenter.Windows
{
	/// <summary>
	/// Interaction logic for ServerSelectionDialog.xaml
	/// </summary>
	public partial class ServerSelectionDialog : Window, IDisposable
	{
		NetComServerFinder _NCF;

		public ServerInfoList _AvailableServers
		{
			get { return _NCF.AvailableServers; }
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="ServerSelectionDialog"/> class.
		/// </summary>
		public ServerSelectionDialog()
		{
			_NCF = new NetComServerFinder();
		}

		public ServerInfo SelectServerDialog()
		{
			_NCF.BeginSearch(Settings.Default.DefaultApplicationPort);

			InitializeComponent();

			bool? result = this.ShowDialog();

			_NCF.EndSearch();
			
			if (result == false)
			{
				return null;
			}
			else
			{
				return ServerSelector.SelectedItem as ServerInfo;
			}
		}

		private void ConnectButton_Click(object sender, RoutedEventArgs e)
		{
			if (ServerSelector.SelectedItem != null)
			{
				this.DialogResult = true;
				this.Close();
			}
		}

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		public void Dispose()
		{
			_NCF.Dispose();
		}
	}
}
